package dao.admins.impl;

import dao.BaseDao;
import dao.admins.IAnnouncementMan;
import pojo.Announcement;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class AnnouncementManImpl implements IAnnouncementMan {
    BaseDao baseDao = new BaseDao();
    @Override
    public List<Announcement> queryAllAnns() {
        List<Announcement> announcements = new ArrayList<>();
        String sql = "select * from announcement";
        try (ResultSet rs = baseDao.executeSelect(sql, null)) {
            while (rs.next()) {
                Announcement announcement = new Announcement();
                setAnn(announcement, rs.getLong("id"), rs.getString("aTitle"), rs.getString("aText"), rs.getTimestamp("aDate"));
                announcements.add(announcement);
            }
            baseDao.closeAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return announcements;
    }

    @Override
    public int addAnn(Announcement announcement) {
        String sql = "insert into announcement(aTitle,aText,aDate) values(?,?,?)";
        Object[] params = {announcement.getaTitle(), announcement.getaText(), announcement.getaDate()};
        int result = baseDao.executeUpdateRows(sql, params);
        baseDao.closeAll();
        return result;
    }

    @Override
    public Announcement queryAnnById(long id) {
        String sql = "select * from announcement where id = ?";
        Announcement announcement = new Announcement();
        Object[] params = {id};
        try (ResultSet rs = baseDao.executeSelect(sql, params)) {
            if (rs.next()) {
                setAnn(announcement, rs.getLong("id"), rs.getString("aTitle"), rs.getString("aText"), rs.getTimestamp("aDate"));
            }
            baseDao.closeAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return announcement;
    }

    @Override
    public int updateAnn(Announcement announcement) {
        String sql = "update announcement set aTitle = ?, aText = ?, aDate = ? where id = ?";
        Object[] params = {announcement.getaTitle(), announcement.getaText(), announcement.getaDate(), announcement.getId()};
        int result = baseDao.executeUpdateRows(sql, params);
        baseDao.closeAll();
        return result;
    }

    @Override
    public int deleteAnn(long id) {
        String sql = "delete from announcement where id = ?";
        Object[] params = {id};
        int result = baseDao.executeUpdateRows(sql, params);
        baseDao.closeAll();
        return result;
    }

    public static final void setAnn(Announcement announcement, long id, String aTitle, String aText, Timestamp aDate) {
        announcement.setId(id);
        announcement.setaTitle(aTitle);
        announcement.setaText(aText);
        announcement.setaDate(aDate);
    }
}
